package com.example.anliku.service.serviceImpl;/**
 * Created by Administrator on 2019/11/12/012.
 */

import com.example.anliku.entity.*;
import com.example.anliku.mapper.*;
import com.example.anliku.service.ExampleService;
import com.github.pagehelper.PageInfo;
import com.example.anliku.service.LuceneService;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.*;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.*;
import org.apache.lucene.search.Sort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.System;
import java.text.ParseException;
import java.util.*;

/**
 * @ClassName LuceneServiceImpl
 * @Description TODO
 * @Author yb
 * @Date 2019/11/12/01218:12
 * @Version 1.0
 **/
@Service
public class LuceneServiceImpl implements LuceneService {
    @Autowired
    private IndexWriter indexWriter;

    @Resource
    private ExampleService exampleService;

    @Override
    public String createProductIndex(List<Example> exampleList) throws IOException {
        System.out.println(exampleList);
        List<Document> docs = new ArrayList<Document>();
        for (Example p : exampleList) {
            Document doc = new Document();
            doc.add(new StoredField("exampleId", p.getExampleId()));
            doc.add(new StoredField("exampleUserId", p.getExampleUserId()));
            doc.add(new StoredField("exampleState", p.getExampleState()));
            doc.add(new StoredField("exampleTypeName", p.getExampleTypeName()));
            doc.add(new StoredField("exampleKnowledge", p.getExampleKnowledgeId()));
            doc.add(new StoredField("exampleClazz", p.getExampleClazz()));
            doc.add(new StoredField("exampleImage", p.getExampleImage()));
            doc.add(new StoredField("exampleBook", p.getExampleBook()));
            doc.add(new StoredField("exampleVideo", p.getExampleVideo()));
            doc.add(new StoredField("exampleCode", p.getExampleCode()));
            doc.add(new StoredField("exampleSeeUserId", p.getExampleSeeUserId()));
            doc.add(new StoredField("examplePublicState", p.getExamplePublicState()));
            doc.add(new StoredField("exampleCheckId", p.getExampleCheckId()));
            doc.add(new StoredField("examplePassTime", String.valueOf(p.getExamplePassTime())));
            doc.add(new StoredField("exampleAdvice", p.getExampleAdvice()));
            doc.add(new StoredField("exampleCommentId", p.getExampleCommentId()));
            doc.add(new StoredField("exampleStartTime", String.valueOf(p.getExampleStartTime())));

            doc.add(new TextField("exampleName", p.getExampleName(), Field.Store.YES));
            doc.add(new TextField("exampleUserName", p.getExampleUserName(), Field.Store.YES));
            doc.add(new TextField("exampleIntroduction", p.getExampleIntroduction(), Field.Store.YES));

//            Double price = p.getPrice();
//            doc.add(new DoublePoint("price", price));
//            doc.add(new StoredField("price", p.getPrice()));
//            doc.add(new DoublePoint("discount", p.getDiscount()));
//            doc.add(new StoredField("discount", p.getDiscount()));
//            doc.add(new DoublePoint("discountRate", p.getDiscountRate()));
//            doc.add(new StoredField("discountRate", p.getDiscountRate()));
//            doc.add(new DoublePoint("cid1", p.getCid1()));
//            // 正排索引用于排序、聚合
//            doc.add(new DoubleDocValuesField("price", price));
//            // 存储到索引库
//            doc.add(new StoredField("cid1", p.getCid1()));
            docs.add(doc);
        }
        indexWriter.addDocuments(docs);
       // indexWriter.updateDocument(docs);
        indexWriter.commit();
      //  indexWriter.close();
        return null;
    }
    @Autowired
    private Analyzer analyzer;

    @Autowired
    private SearcherManager searcherManager;

    @Override
    public PageQuery searchProduct(PageQuery pageQuery) throws Exception, ParseException {
        searcherManager.maybeRefresh();
        IndexSearcher indexSearcher = searcherManager.acquire();
//        Analyzer analyzer = new IKAnalyzer(true);
//        DirectoryReader directoryReader = DirectoryReader.open(FSDirectory.open(Paths.get(LuceneConfig.LUCENEINDEXPATH)));
//        //索引查询器
//        IndexSearcher indexSearcher = new IndexSearcher(directoryReader);

        Example params = pageQuery.getParams();
        Map<String, String> queryParam = pageQuery.getQueryParam();
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        Sort sort = new Sort();
        // 排序规则
        com.example.anliku.entity.Sort sort1 = pageQuery.getSort();
        if (sort1 != null && sort1.getOrder() != null) {
            if ("ASC".equals(sort1.getOrder().toUpperCase())) {
                sort.setSort(new SortField(sort1.getField(), SortField.Type.FLOAT, false));
            } else if ("DESC".equals((sort1.getOrder()).toUpperCase())) {
                sort.setSort(new SortField(sort1.getField(), SortField.Type.FLOAT, true));
            }
        }

        // 模糊匹配,匹配词
        String exampleIntroduction = params.getExampleIntroduction();
        if (params != null && params.getExampleIntroduction() != null) {
            // 输入空格,不进行模糊查询
            if (!"".equals(exampleIntroduction.replaceAll(" ", ""))) {
                builder.add(new QueryParser("exampleIntroduction", analyzer).parse(exampleIntroduction), BooleanClause.Occur.MUST);
            }
        }

        String exampleName = params.getExampleName();
        if (params != null && params.getExampleName() != null) {
            // 输入空格,不进行模糊查询
            System.out.println("1111111");
            if (!"".equals(exampleName.replaceAll(" ", ""))) {
                builder.add(new QueryParser("exampleName", analyzer).parse(exampleName), BooleanClause.Occur.MUST);
                System.out.println(builder.build());
            }
        }
        String exampleUserName = params.getExampleUserName();
        if (params != null && params.getExampleUserName() != null) {
            // 输入空格,不进行模糊查询
            if (!"".equals(exampleUserName.replaceAll(" ", ""))) {
                builder.add(new QueryParser("exampleUserName", analyzer).parse(exampleUserName), BooleanClause.Occur.MUST);
            }
        }

//        // 精确查询
//        if (params != null && params.getCid1() != null) {
//            builder.add(new TermQuery(new Term("cid1", String.valueOf(params.getCid1()))), BooleanClause.Occur.MUST);
//        }
//        if (params != null && params.getGetEndTimeForL() != null) {
//            builder.add(new TermQuery(new Term("cid1", String.valueOf(params.getCid1()))), BooleanClause.Occur.MUST);
//        }
//        if (queryParam.get("lowerPrice") != null && queryParam.get("upperPrice") != null) {
//            // 价格范围查询
//            builder.add(FloatPoint.newRangeQuery("price", Float.parseFloat(queryParam.get("lowerPrice")),
//                    Float.parseFloat(queryParam.get("upperPrice"))), BooleanClause.Occur.MUST);
//        }
        PageInfo pageInfo = pageQuery.getPageInfo();
        TopDocs topDocs = indexSearcher.search(builder.build(), pageInfo.getPageNum() * pageInfo.getPageSize(), sort);

        pageInfo.setTotal(topDocs.totalHits.value);
        ScoreDoc[] hits = topDocs.scoreDocs;

        List<HashMap> pList = new ArrayList<HashMap>();
        for (int i = 0; i < hits.length; i++) {
            Document doc = indexSearcher.doc(hits[i].doc);
            System.out.println(doc.get("exampleId"));
            HashMap HashMaps = exampleService.Example(Integer.valueOf(doc.get("exampleId")));
            pList.add(HashMaps);
        }
        pageQuery.setPageInfo(pageInfo);
        pageQuery.setResults(pList);
        return pageQuery;
    }

    @Override
    public void deleteProductIndexById(String id) throws IOException {
        indexWriter.deleteDocuments(new Term("id",id));
        indexWriter.commit();
    }
}
